<?php

namespace app\admin\controller;

use think\Request;
use app\admin\model\AuthRule as AuthRuleModel;

class AuthRule extends Base
{
    private $authRule;

    function initialize()
    {
        parent::initialize();
        $this->authRule = new AuthRuleModel();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $rules = $this->authRule->authRuleTree();
        $this->assign('rules', $rules);
        return view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

        // 接收数据
        $param = input('post.');

        // 查找上一级的level
        $plevel = AuthRuleModel::where('id', $param['pid'])->value('level');
        if ($plevel || $plevel === 0) {
            $param['level'] = $plevel + 1;
        }

        // 规则添加数据
        $result = $this->authRule->save($param);
        // 对应的用户组也要添加相应的规则

        if ($result) {
            return redirect('/auth_rule');
        }

        $this->error('添加权限规则失败!');

    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        // 当前权限规则
        $rule = AuthRuleModel::get($id);

        // 上级权限规则
        $prule = AuthRuleModel::get($rule['pid']);

        $rule['pname'] = $prule['name'];

        return $rule;
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        // 当前权限规则
        $rule = AuthRuleModel::get($id);

        return $rule;
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {

        // 接收参数
        $param = input('put.');
        unset($param['_method']);

        // 修改level
        // 查找上一级的level
        $plevel = AuthRuleModel::where('id', $param['pid'])->value('level');

        if ($plevel !== null) {
            $param['level'] = $plevel + 1;
        }

        $result = $this->authRule->save($param, ['id' => $id]);
        if ($result !== false) {
            return redirect('/auth_rule');
        }
        $this->error('更新权限失败!');

    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {

        if (!request()->isDelete()) {
            return ;
        }

        // 删除所有的子权限规则
        $this->authRule->recursiveDelSonRules($id);

        $result = AuthRuleModel::destroy($id);
        if ($result !== false) {
            return 1;
        }
        return 0;
    }

}
